import jsonrpc from '@/libs/jsonrpc'
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    paticipantID: undefined,
    currentUser: undefined,
    userName: '',
    userId: '',
    avatarImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    access: [],

    is_admin : false,
    // 是否已经在自动登录时重新获取用户状态
    hasGetInfo: false,
    
    profile : undefined,
  },
  mutations: {
    login (state, result) {
      if (result.id) {
        window.localStorage.setItem('backend.paticipant.id', result.id)
        state.paticipantID = result.id
        state.token = result.id
        setToken(result.id)
      }
      if (result.key) {
        window.localStorage.setItem('backend.paticipant.key', result.key)
      }
      if (result.user) {
        state.currentUser = result.user
        state.access = result.user.access
        state.is_admin = result.user.is_admin
      }
      if (result.ou) {
        state.currentOU = result.ou
      }
    },
    logout (state) {
      window.localStorage.setItem('backend.paticipant.id', '')
      window.localStorage.setItem('backend.paticipant.key', '')
      state.paticipantID = ''
      state.token = ''
      setToken('')
      state.currentUser = null
      state.access = []
      state.currentOU = null
    },
    setAvatar (state, avatarPath) {
      state.avatarImgPath = avatarPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin ({ state, commit }, { account, password }) {
      commit('startLoading')
      return new Promise((resolve, reject) => {
        jsonrpc('backend@user.login', [{
          account: account,
          password: password
        }], (err, res) => {
          if (err) {
            commit('handleError', err)
            reject(err)
          } else {
            commit('login', res)
            commit('finishLoading')
            resolve(res)
          }
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        commit('setTagNavList', [])
        commit('logout')
        resolve()
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      commit('startLoading')
      return new Promise((resolve, reject) => {
        if (!state.currentUser) {
          jsonrpc.doParticipant((err, res) => {
            if (err) {
              commit('handleError', err)
              commit('logout')
              reject(err)
            } else {
              commit('login', res)
              commit('setHasGetInfo', true)
              commit('finishLoading')
              resolve(state.currentUser)
            }
          })
        } else {
          commit('finishLoading')
          resolve(state.currentUser)
        }
      })
    },
    // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    getUnreadMessageCount ({ state, commit }) {},
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    getMessageList ({ state, commit }) {},
    // 根据当前点击的消息的id获取内容
    getContentByMsgId ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        let contentItem = state.messageContentStore[msg_id]
        if (contentItem) {
          resolve(contentItem)
        } else {
          getContentByMsgId(msg_id).then(res => {
            const content = res.data
            commit('updateMessageContentStore', { msg_id, content })
            resolve(content)
          })
        }
      })
    },
    // 把一个未读消息标记为已读
    hasRead ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        hasRead(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageUnreadList',
            to: 'messageReadedList',
            msg_id
          })
          commit('setMessageCount', state.unreadCount - 1)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 删除一个已读消息到回收站
    removeReaded ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        removeReaded(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageReadedList',
            to: 'messageTrashList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 还原一个已删除消息到已读消息
    restoreTrash ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        restoreTrash(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageTrashList',
            to: 'messageReadedList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
